package com.heima.admin.interceptor;

import com.heima.admin.thread.AdUserThreadLocal;
import com.heima.model.admin.pojos.AdUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author itheima
 * @since 2022-07-10
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头
        // 通过请求头获取userId
        String userId = request.getHeader("userId");

        // 判空 -> 阻止 -> return false
        if (StringUtils.isEmpty(userId)) {
            log.warn("用户没有登录");
            return false;
        }

        // 不为空 -> 存放到ThreadLocal
        // 1. 创建ThreadLocal类（get、set）
        // 2. 调用ThreadLocal类的set方法，往里面存储数据
        AdUser adUser = new AdUser();
        adUser.setId(Integer.parseInt(userId));
        AdUserThreadLocal.set(adUser);

        return true;
    }
}
